import React from 'react'
import { Form,Input,Button } from 'antd-mobile'
import { loginApi,loginCodeApi } from '../../api'
import { loginsuccess } from '../../store/userSlice/userSlice'
import useTelDown from '../../hooks/useTelDown'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
function Login() {
  let [form]=Form.useForm()
  const navigate=useNavigate()
  const dispatch=useDispatch()

  const {isCurt,count,reset,start}=useTelDown(60,()=>{
    reset()
  })

  const onFinish=async(value)=>{
    const resp=await loginApi(value)
    console.log(resp)
    const {code,data,message}=resp.data
    if(code===200){
      alert(message)
      navigate('/home/shouye')
      dispatch(loginsuccess(data))
      localStorage.setItem('token',data.token)
    }else{
      alert(message)
    }
  }

  
  const getReadom=()=>{
    form
    .validateFields(['tel'])
    .then(async({tel})=>{
      const resp=await loginCodeApi(tel)
      const telCode=(resp.data.data)
      console.log(telCode)

      form.setFieldValue('telCode',telCode)

      start()
    })
    .catch(()=>{})
  }
  return (
    <div>
      <Form
      form={form}
        onFinish={onFinish}
        layout='horizontal'
        footer={
          <Button block type='submit' color='primary'>
            提交
          </Button>
        }
      >
        <Form.Item
          name='tel'
          rules={[
            { required: true, message: '手机号不能为空' },
            {pattern:/^1[3-9]\d{9}$/,message:"请输入正确的手机号"}]}
        >
          <Input placeholder='请输入手机号' />
        </Form.Item>
        <Form.Item name="telCode" extra={
          <Button type="submit" color="primary" onClick={()=>getReadom()} disabled={isCurt}>
            {isCurt?`已发送${count}秒`:"获取验证码"}
          </Button>
        }>
          <Input placeholder='请输入验证码'></Input>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login
